package com.sharemarking.wa.platform.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.wa.common.Page;
import com.sharemarking.wa.common.ResponseParams;
import com.sharemarking.wa.common.eum.OrderStateEum;
import com.sharemarking.wa.common.exception.RequestException;
import com.sharemarking.wa.common.entity.*;
import com.sharemarking.wa.common.eum.OrderOperateTypeEum;
import com.sharemarking.wa.platform.dto.orderManagement.OrderListDto;
import com.sharemarking.wa.platform.dto.address.AddressListDto;
import com.sharemarking.wa.platform.mapper.*;
import com.sharemarking.wa.platform.service.OrderDelayQueue.OrderDelay;
import com.sharemarking.wa.platform.service.OrderDelayQueue.OrderQueue;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.sharemarking.wa.common.SysHttpStatus.REQUIRED_PARAMS_ERROR;

/**
 * @author dxy
 */
@Service
public class OrderManagementService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecurityService ss;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderManagementMapper orderManagementMapper;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private OrgMemberMapper orgMemberMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderQueue orderQueue;
    @Autowired
    private GeocodingService geocodingService;
    @Autowired
    private JGPushService jgPushService;
    @Autowired
    private ReceiveOrderManagementMapper receiveOrderManagementMapper;

    public ResponseParams<?> chooseAddress() throws Exception {
        Integer memberId = ss.getCurrentUserId();

        List<AddressListDto> addressListDtos = orderManagementMapper.getChooseAddress(memberId);

        return ResponseParams.ok(addressListDtos);
    }


    @Transactional(rollbackFor = Exception.class)
    public ResponseParams<?> accept() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");
        String addressId = request.getParameter("addressId");


        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }

        if (StringUtils.isEmpty(addressId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("addressId"));
        }

        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("code", code));
        OrgMember orgMember = orgMemberMapper.selectOne(new QueryWrapper<OrgMember>().select("org_id").eq("member_id", memberId));

        if (order == null || !order.getState().equals(OrderStateEum.RECEIPT.getKey())) {
            throw RequestException.create(ResponseParams.isDataError("该订单已被接单，请进行支付"));
        }

        if (order.getReceiveOrgId() != null && !order.getReceiveOrgId().equals(orgMember.getOrgId())) {
            throw RequestException.create(ResponseParams.isDataError("错误的业务"));
        }

        if (orderManagementMapper.isAccept(order.getId()) != 0) {
            throw RequestException.create(ResponseParams.isDataError("请不要重复接单"));
        }

        Address address = orderManagementMapper.getAddress(Integer.valueOf(addressId), memberId);
        if (StringUtils.isEmpty(address)) {
            throw RequestException.create(ResponseParams.isDataError("地址错误"));
        }

        //新增卸货地址
        OrderAddress orderAddress = new OrderAddress();
        orderAddress.setType(1);//卸货地址
        orderAddress.setOrderId(order.getId());
        orderAddress.setCreateDate(new Date());
        orderAddress.setProvince(address.getProvince());
        orderAddress.setCity(address.getCity());
        orderAddress.setArea(address.getArea());
        orderAddress.setAddress(address.getAddress());
        orderAddressMapper.insert(orderAddress);

        String endAddress = address.getProvince() + address.getCity() + address.getArea() + address.getAddress();
        //更新订单状态
        order.setState(OrderStateEum.UNPAID.getKey());
        order.setCode(code);
        order.setReceiveOrgMemberId(memberId);
        order.setReceiveOrgId(orgMember.getOrgId());
        //获取两地距离
        System.out.println(orderManagementMapper.getOrderStartAddress(order.getId()));
        System.out.println(endAddress);
        Integer distance = geocodingService.getDistanceFromTwoPlaces(orderManagementMapper.getOrderStartAddress(order.getId()), endAddress);
        order.setDistance(distance);
        //根据公式计算距离和费用:距离(KM)乘以废品吨数再乘以3
//        order.setTransportFees((int)(order.getCarWeight() * 0.01 * distance * 2.5 * 1000));

        order.setTransportFees(1);
        //根据公式计算价格
//        上线正式之后，正式环境，先调成12公里内起步价250元，再加上6元一公里吧
//        Integer fess;
//        if (distance <= 12) {
//            fess = 250;
//        } else {
//            fess = (distance - 12) * 6 + 250;
//        }
//        order.setTransportFees(fess * 100);
 //       order.setTransportFees(1);
        order.setUpdateDate(new Date());
        orderManagementMapper.acceptOrder(order);


        //发送消息
        String messageStr = "您好，尾号为" + receiveOrderManagementMapper.getCodeById(order.getParentId()).substring(order.getCode().length() - 10) + "的总订单已被" + orgMapper.getOrgNameById(order.getReceiveOrgId()) + "接单，总订单共发布了" + receiveOrderManagementMapper.getOrderWasteInfoStr(order.getParentId()) +
                "，本次接单" + receiveOrderManagementMapper.getOrderWasteInfoStr(order.getId()) + "，总单余下未接单" + receiveOrderManagementMapper.getRemainOrderWasteInfoStr(order.getParentId());
        jgPushService.pushTag(messageStr, order.getSendOrgMemberId());

        //将订单id缓存入延迟队列
//        OrderDelay orderDelay = new OrderDelay(order.getId(), 2 * 60 * 60 * 1000);
//        orderQueue.getQueue().offer(orderDelay);
        return ResponseParams.ok(null);
    }


    public ResponseParams<?> finishOrder() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");

        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("code", code));

        if (order == null) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }

        if (!order.getReceiveOrgMemberId().equals(memberId)) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }

        Order newOrder = new Order();
        newOrder.setId(order.getId());
        newOrder.setState(OrderStateEum.CHILD_ORDER_FINISH.getKey());
        int a = OrderStateEum.CHILD_ORDER_FINISH.getKey();
        newOrder.setCompleteTime(new Date());
        newOrder.setUpdateDate(new Date());
        orderManagementMapper.finishOrder(newOrder);

        String messageStr = "您好，尾号为" + order.getCode().substring(order.getCode().length() - 10) + "的子订单，" + orgMapper.getOrgNameById(order.getReceiveOrgId()) + "已确认收货";
        jgPushService.pushTag(messageStr, order.getSendOrgMemberId());
        jgPushService.pushTag(messageStr, order.getReceiveOrgMemberId());
        jgPushService.pushTag(messageStr, memberId);
        return ResponseParams.ok(null);
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseParams<?> cancelAcceptOrder() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");

        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }
        //查找机构id，目的是为了判断是不是指定
        Integer orgId = orgMemberMapper.selectOne(new QueryWrapper<OrgMember>().select("org_id").eq("member_id", memberId)).getOrgId();
        if (orgId == null) {
            return null;
        }
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().select("id","send_org_member_id").eq("code", code).eq("receive_org_id", orgId));
        if (order == null) {
            return null;
        }
        //wa_order删除该订单
        orderManagementMapper.cancelOrder(order.getId());
        //wa_order_detail 删除该订单
        orderDetailMapper.delete(new QueryWrapper<OrderDetails>().eq("order_id", order.getId()));
        //wa_order_address 删除该订单
        orderAddressMapper.delete(new QueryWrapper<OrderAddress>().eq("order_id", order.getId()));

        String messageStr = "您好，尾号为" + code.substring(code.length() - 10) + "的子订单已被" + orgMapper.getOrgNameById(orgId) + "取消";
        jgPushService.pushTag(messageStr, order.getSendOrgMemberId());

        return ResponseParams.ok(null);
    }

}
